﻿using System;
using System.Linq;
using System.Reflection;

namespace Infrastucture
{
    public static class ModelConverter
    {
        // eventualy may want to make this more robust and add come checks to make sure its working ok

        public static T ToModel<T>(object obj)
        {
            if (obj == null)
                return default(T);

            // going to 
            Type from = obj.GetType();
            Type to = typeof(T);
            var model = Activator.CreateInstance(to);


            // get all properties and find a match of the name in the TO 
            var fromProps = from.GetProperties();
            var toProps = to.GetProperties();

            foreach (var fp in fromProps)
            {
                var tp = toProps.FirstOrDefault(x => x.Name == fp.Name);

                if (tp != null)
                {
                    var doNotConvert = tp.GetCustomAttributes(typeof(DoNotConvertAttribute), false).FirstOrDefault();

                    if (doNotConvert == null)
                    {
                        object value = fp.GetValue(obj, null);
                        tp.SetValue(model, value, null);
                    }
                }
            }

            return (T)model;
        }
    }
}
